import { defineStore } from 'pinia'
import { getCode, loginCode } from '@/api/email/index'
import type { codeState, backLogin } from '@/api/email/type'
// 引入router组件
import { router } from "@/router/index"
import { useRoute, useRouter } from 'vue-router'
import type { RefSymbol } from '@vue/reactivity'

interface userData {
  data: {
    name: string
    token: string
  }
}
let $router = useRouter()
let $route = useRoute()


export const useUserStore = defineStore('user', {
  state: () => {
    return {
      // 显示页面
      dialogTableVisible: false,
      phoneCode: '' as string,
      userData: JSON.parse(localStorage.getItem('userData') as string),
        token: JSON.parse(localStorage.getItem('userData') as any) || '',
      redirect:''
    }
  },
  actions: {
    // 更改登录显示与否
    visDialog() {
      this.dialogTableVisible = true
    },
    closeDia() {
      this.dialogTableVisible = false
    },
    async onceCode(phone: string) {
      let result: codeState = await getCode(phone)
      if (result.code == 200 && result.data != null) {
        this.phoneCode = result.data
      } else {
        return Promise.reject(new Error('获取失败'))
      }
    },
    // 用户登录
    async userLogin(data: any) {
    
      let result: backLogin = await loginCode(data)
      if (result.code == 200) {
        //@ts-ignore
        this.userData = result.data
        this.token = result.data.token
        localStorage.setItem('userData', JSON.stringify(this.userData))
        return 'ok'
      }
    },
    // 退出登录
    quitLogin() {
      this.token = ''
      this.userData = {}

      localStorage.removeItem('userData')
    },
    queryData() {
      let timer = setInterval(() => {
        if (localStorage.getItem('userData')) {
          let a = JSON.parse(localStorage.getItem('userData') as string)
          this.dialogTableVisible = false
          this.userData = a
          this.token = a.token
        }
      }, 100)
    }
  },
  getters: {}
})
